

export function longestCommonSubsequence(text1, text2) {
  const m = text1.length;
  const n = text2.length;
  const dp = Array.from(Array(m + 1), () => Array(n + 1).fill(0));

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (text1[i - 1] === text2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }
  return dp[m][n];
}


/**
* 相似度对比
* @param s 文本1
* @param t 文本2
* @param f 小数位精确度，默认2位
* @returns {string|number|*} 百分数前的数值，最大100. 比如 ：90.32
*/
export function resultAccuracy(s, t, f = 2) {
    if (!s || !t) {
      return 0
    }
    if (s === t) {
      return 100
    }
    var l = s.length > t.length ? s.length : t.length
    var n = s.length
    var m = t.length
    var d = []
    f = f || 2
    var min = function (a, b, c) {
      return a < b ? (a < c ? a : c) : b < c ? b : c
    }
    var i, j, si, tj, cost
    if (n === 0) return m
    if (m === 0) return n
    for (i = 0; i <= n; i++) {
      d[i] = []
      d[i][0] = i
    }
    for (j = 0; j <= m; j++) {
      d[0][j] = j
    }
    for (i = 1; i <= n; i++) {
      si = s.charAt(i - 1)
      for (j = 1; j <= m; j++) {
        tj = t.charAt(j - 1)
        if (si === tj) {
          cost = 0
        } else {
          cost = 1
        }
        d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
      }
    }
    let res = (1 - d[n][m] / l) * 100
    return res.toFixed(f)
}


/**
 * 流畅性
 */
export function calculateFluency(text1, text2) {
    const m = text1.length
    const n = text2.length

    const dp = Array.from(Array(m + 1), () => Array(n + 1).fill(0))

    for (let i = 0; i <= m; i++) {
      for (let j = 0; j <= n; j++) {
        if (i === 0) {
          dp[i][j] = j
        } else if (j === 0) {
          dp[i][j] = i
        } else if (text1[i - 1] === text2[j - 1]) {
          dp[i][j] = dp[i - 1][j - 1]
        } else {
          dp[i][j] = 1 + Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])
        }
      }
    }

    const fluency = ((1 - dp[m][n] / Math.max(m, n)) * 100).toFixed(2)
    return fluency
}